﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using TestCommunityMvvmToolkit.Presentation;

namespace TestCommunityMvvmToolkit
{
    public class AliveViewModel : BindableBase
    {
        private object? attached_view;

        protected virtual void ViewClosed(object? sender, EventArgs e)
        {
            Trace.TraceInformation(sender?.GetType().Name + "ViewClosed()");
        }

        protected virtual void ViewUnloaded(object? sender, RoutedEventArgs e)
        {
            Trace.TraceInformation(sender?.GetType().Name + "ViewUnloaded()");

        }

        protected virtual void ViewLoaded(object? sender, RoutedEventArgs e)
        {
            Trace.TraceInformation(sender?.GetType().Name + "ViewLoaded()");
        }

        protected virtual object? AttachView()
        {
            var view = ViewAware.Aware(this);
            if (view is FrameworkElement fev)
            {
                LoadedWeakEventManager.AddHandler(fev, ViewLoaded);
                UnloadedWeakEventManager.AddHandler(fev, ViewUnloaded);

                fev.DataContext = this;
            }
            if (view is Window wv)
            {
                WeakEventManager<Window, EventArgs>.AddHandler(wv, nameof(wv.Closed), ViewClosed);
            }
            return view;
        }

        public void Activate()
        {
            attached_view = AttachView();
            if (attached_view is Window wv)
            {
                wv.Show();
            }
        }
    }
}